package com.chunxuan.langquan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.Banner;
import com.chunxuan.langquan.dao.bean.CourseBean;
import com.chunxuan.langquan.dao.bean.SubjectBean;
import com.chunxuan.langquan.dao.bean.UserInfo;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.dao.http.APIRetrofit2;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.activity.GuidActivity;
import com.chunxuan.langquan.ui.activity.SearchCourseActivity;
import com.chunxuan.langquan.ui.activity.WebViewActivity;
import com.chunxuan.langquan.ui.adapter.CourseAdapter;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 首页
public class Home1Fragment extends BaseFragment implements HandlerUtil.OnReceiveMessageListener {
    private ViewPager vp;

    //    private Banner banner;
    private static Home1Fragment fragment;
    private RelativeLayout rl_search;// 精选文章,报告解读,下单,搜索
    private ImageView iv_notice, iv_back_vv;// 消息, 返回
    private TextView vUnreadCount;
    private List<CourseBean> courseBeanList = new ArrayList<>();
    private RecyclerView rvCourse;
    private List<SubjectBean> subjectBeanList = new ArrayList<>();

    private List<Banner> bannerList = new ArrayList<>();// banner的数据
    private VpAdapter adapter;// banner

    private int currIndex = 0;
    private HandlerUtil.HandlerHolder handler;

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 21031052) {// 轮播
            handler.removeMessages(21031052);
            try {
                currIndex++;
                if (currIndex >= bannerList.size()) {
                    currIndex = 0;
                }
                vp.setCurrentItem(currIndex, true);
                handler.sendEmptyMessageDelayed(21031052, 5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Home1Fragment() {

    }

    public static Home1Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home1Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new HandlerUtil.HandlerHolder(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home1, container, false);
//        banner = v.findViewById(R.id.banner);// Banner布局
        rvCourse = v.findViewById(R.id.rv_fragment_course);
        iv_back_vv = v.findViewById(R.id.iv_back_vv);
        if(Global.IS_SHOW==0){
            iv_back_vv.setVisibility(View.INVISIBLE);
        }else if(Global.IS_SHOW==1){
            iv_back_vv.setVisibility(View.VISIBLE);
        }
        iv_notice = v.findViewById(R.id.iv_shopping_market_cart);
        rl_search = v.findViewById(R.id.rl_search);
        vUnreadCount = v.findViewById(R.id.vUnreadCount);
        vp = v.findViewById(R.id.vp);

        adapter = new VpAdapter();
        vp.setAdapter(adapter);

        setListeners();

        reqBannerList();// 请求banner列表
        courseCenter();

        return v;
    }

    private void setListeners() {
        setOnClickListener(iv_notice, rl_search, iv_back_vv);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_search:// 搜索
                startActivity(SearchCourseActivity.class);
                break;
            case R.id.iv_shopping_market_cart:// 消息
//            startActivityForResult(new Intent(getActivity(), MsgListActivity.class), 1001);
                break;
            case R.id.iv_back_vv:
                startActivity(GuidActivity.class);
                getActivity().finish();
                break;
        }
    }

    // 请求首页banner
    private Disposable reqBannerList() {
        return APIRetrofit2.getDefault().reqBannerList(Global.HEADER, 1)
                .compose(RxUtil.<BaseResult2<List<Banner>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Banner>>>() {
                    @Override
                    public void accept(BaseResult2<List<Banner>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        bannerList = listBaseResult2.getData();
                        adapter.notifyDataSetChanged();

                        handler.sendEmptyMessageDelayed(21031052, 5000);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable courseCenter() {
        return APIRetrofit.getDefault().courseCenter(Global.HEADER, "")
                .compose(RxUtil.<BaseResult2<List<CourseBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<CourseBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<CourseBean>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<CourseBean> courseList = result2.getData();
                            courseBeanList = courseList;
                            if (!isDataEmpty(courseList)) {
                                Logg.e("==课程中心==" + courseList.get(0).getList().get(0).getName());
                                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
                                rvCourse.setLayoutManager(gridLayoutManager);
                                if (courseBeanList != null && courseBeanList.size() > 0) {
                                    int index = 0;
                                    subjectBeanList.clear();
                                    for (int i = 0; i < courseBeanList.size(); i++) {
                                        for (int t = 0; t < courseBeanList.get(i).getList().size(); t++) {
                                            subjectBeanList.add(courseBeanList.get(i).getList().get(t));
                                        }
                                    }
                                    CourseAdapter courseAdapter = new CourseAdapter(getContext(), subjectBeanList);
                                    for (int i = 0; i < courseBeanList.size(); i++) {
                                        if (i == 0) {
                                            index = i;
                                            courseAdapter.addTitle(0, courseBeanList.get(0).getName());
                                        } else {
                                            index += courseBeanList.get(i - 1).getList().size() + 1;
                                            courseAdapter.addTitle(index, courseBeanList.get(i).getName());
                                        }
                                    }
                                    rvCourse.setAdapter(courseAdapter);
                                }
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取课程列表失败");
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
    }

    private UserInfo userInfo;

    private Disposable getUserInfo() {
        return APIRetrofit.getDefault().userInfo(Global.HEADER, "")
                .compose(RxUtil.<BaseResult2<UserInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UserInfo>>() {
                    @Override
                    public void accept(BaseResult2<UserInfo> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            userInfo = result2.getData();
                            Logg.i("==用户信息-昵称==" + result2.getData().getNickname());
                            Global.USER_INFO = userInfo;
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        Logg.i("获取用户信息失败");
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    // banner adapter
    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView iv = new ImageView(getActivity());
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            GlideUtil.loadImg(bannerList.get(position).getAd_image(), iv);

            container.addView(iv);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(bannerList.get(position).getAd_url())){
                        Intent intent=new Intent(getContext(), WebViewActivity.class);
                        intent.putExtra("ad_url",bannerList.get(position).getAd_url());
                        startActivity(intent);
                    }
                }
            });
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }
}